package com.bianmaba.services.datacollection.quartiz;

import com.bianmaba.beans.datacollection.TaskInstance;
import com.bianmaba.beans.datacollection.TaskRunLog;
import com.bianmaba.jobs.supports.CollectionResult;
import com.bianmaba.jobs.supports.JobParameter;
import com.bianmaba.services.datacollection.ITaskInstanceService;
import com.bianmaba.services.datacollection.TaskRunLogWriter;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;


@Component
public class GlobalJobListener implements org.quartz.JobListener {
    @Autowired
    private ITaskInstanceService taskInstanceService;
    @Autowired
    private TaskRunLogWriter logWriter;

    private static Logger logger = LoggerFactory.getLogger(GlobalJobListener.class);

    @Override
    public String getName() {
        String name = getClass().getSimpleName();
        logger.info(" listener name is:" + name);
        return name;
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        logger.info("JobDataMap数据检查：" + jobName);

        Map<String, Object> jobDataMap = context.getMergedJobDataMap().getWrappedMap();
        List<Map<String, String>> parameters = (List<Map<String, String>>) jobDataMap.get(JobParameter.COLLECTION_PARAMETERS.getName());
        processingParameters(parameters);
    }

    private void processingParameters(List<Map<String, String>> parameters) {
        //TODO 实现参数处理，将动态参数部份填写实值
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        logger.info(jobName + " was vetoed and not executed");
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {

        JobDataMap dataMap = context.getMergedJobDataMap();
        String taskInstanceId = dataMap.getString(JobParameter.TASK_INSTANCE_ID.getName());
        if (jobException != null) {
            Integer status = TaskInstance.Status.EXCEPTIONAL.getIndex();
            TaskInstance taskInstance = taskInstanceService.updateStatus(taskInstanceId, status);
            String jobName = context.getJobDetail().getKey().getName();
            logger.info("\"{}\" was executed,result={}", jobName, taskInstance.getStatus());
        }


    }
}